using UnityEngine;
using EchoFramework;

/// <summary>
/// 关卡Item
/// </summary>
public class LevelItem : MonoBehaviour
{
    private PrefabBinder prefabBinder;
    private EchoButton levelBtn;
    private RectTransform passRectTrans;
    private RectTransform lockRectTrans;
    private RectTransform unLockRecTrans;
    private EchoText passTxt;
    private EchoText lockTxt;
    private EchoText unlockTxt;
    
    /// <summary>
    /// 关卡Item数据
    /// </summary>
    private LevelItemData levelItemData;
    
    private void Awake()
    {
        prefabBinder = GetComponent<PrefabBinder>();
        levelBtn = prefabBinder.Find("LevelBtn").GetComponent<EchoButton>();
        levelBtn.onClick.AddListener(OnClickLevelBtn);
        passRectTrans = prefabBinder.Find("PassRectTrans").GetComponent<RectTransform>();
        lockRectTrans = prefabBinder.Find("LockRectTrans").GetComponent<RectTransform>();
        unLockRecTrans = prefabBinder.Find("UnLockRecTrans").GetComponent<RectTransform>();
        passTxt = prefabBinder.Find("passTxt").GetComponent<EchoText>();
        lockTxt = prefabBinder.Find("lockTxt").GetComponent<EchoText>();
        unlockTxt = prefabBinder.Find("unlockTxt").GetComponent<EchoText>();
    }
    
    /// <summary>
    /// 设置数据
    /// </summary>
    /// <param name="data">关卡数据</param>
    public void SetData(LevelItemData data)
    {
        levelItemData = data;
        Refresh();
    }

    /// <summary>
    /// 刷新Item
    /// </summary>
    private void Refresh()
    {
        if (levelItemData == null)
        {
            Debug.LogError("关卡数据为Null！");
            return;
        }

        passTxt.text = levelItemData.Level.ToString();
        lockTxt.text = levelItemData.Level.ToString();
        unlockTxt.text = levelItemData.Level.ToString();
        passRectTrans.gameObject.SetActive(levelItemData.LevelStatus == LevelStatusEnum.Pass);
        lockRectTrans.gameObject.SetActive(levelItemData.LevelStatus == LevelStatusEnum.Lock);
        unLockRecTrans.gameObject.SetActive(levelItemData.LevelStatus == LevelStatusEnum.UnLock);
        levelBtn.interactable = levelItemData.LevelStatus != LevelStatusEnum.Lock;
    }
    
    /// <summary>
    /// 点击关卡
    /// </summary>
    private void OnClickLevelBtn()
    {
        if (levelItemData == null)
        {
            Debug.LogError("关卡数据为Null！");
            return;
        }

        if (levelItemData.LevelStatus == LevelStatusEnum.Lock && !GameEntry.Instance.UnlockAll)
        {
            Debug.LogWarning("当前关卡未解锁");
            return;
        }
        
        UIViewManager.Instance.OpenWindow(UIViewID.GameView);
        UIViewManager.Instance.CloseWindow(UIViewID.SelectLevelView);
        MapLogicModule.Instance.LoadMapLevel(levelItemData.Level);

    }
}